package com.gz.controller;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import com.gz.common.MessageService;
import com.gz.common.model.Message;
import com.gz.utils.Response;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Page;

/**
 * Created by gongzhen on 2018/6/2.
 */
public class MessageController extends Controller{

    public void getMessagePage(){
        int pageNum=getParaToInt("pageNum",1);
        int pageSize=getParaToInt("pageSize",10);
        Page<Message> messagePage= MessageService.getService().getMessagePage(pageNum,pageSize);
        renderJson(Response.responseJson(200,"成功",messagePage));
    }

    public void saveMessage(){
        Message message=getBean(Message.class,"");
        if(message.getId()==null){
            message.save();
        }else{
            message.update();
        }
        renderJson(Response.responseJson(200,"成功",message));
    }

    public void notifyMessage(){
        Message message=getBean(Message.class,"");
        if(message.getId()!=null){
            JPushClient jpushClient = new JPushClient(PropKit.get("jpush_master_secret"),PropKit.get("jpush_app_key"), null, ClientConfig.getInstance());
            PushPayload payload = PushPayload.alertAll(message.getContent());
            try {
                PushResult result = jpushClient.sendPush(payload);
                renderJson(Response.responseJson(200,"成功",result));
            } catch (APIConnectionException e) {
                // Connection error, should retry later
                renderJson(Response.responseJson(500,"失败",e.getMessage()));
            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                renderJson(Response.responseJson(500,"失败",e.getMessage()));
            }
        }
    }

    public static PushPayload buildPushObject_all_all_alert() {
        return PushPayload.alertAll("test");
    }

    public void delMessage(){
        Message message=Message.dao.findById(getParaToInt("id",0));
        message.delete();
        renderJson(Response.responseJson(200,"删除成功"));
    }
}
